/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package core.worker;

import core.manager.TQueueManager;
import core.util.COREServiceRegistry;
import org.apache.log4j.Logger;

/**
 * Questa classe si occupa di monitorare la coda dei worker.
 * @author Vincenzo Merlo, Scuderi Giovanni Luca, Paolo Giuffrida
 */
public class WorkerQueueMonitor implements Runnable {

    volatile Worker worker;
    private final Logger logger = COREServiceRegistry.getLogger(WorkerQueueMonitor.class.toString());

    /**
     *
     * @param man
     */
    public WorkerQueueMonitor(Worker man) {
        this.worker = man;
    }

    /**
     *
     */
    public void run() {
        final TQueueManager queue = (TQueueManager) this.worker.getTQueueManager();
        //check queue is not empty
        synchronized (queue) {
            try {
                logger.info("WAIT!"); // NON CAMBIARE
                queue.wait();
                logger.info("RUN!");
                while (true) {         // TODO: VERIFICARE
                    logger.info("SCHEDULE!!");
                    worker.exec(worker.getTQueueManager().dequeue());
                    if (worker.getTQueueManager().gettQueue().isEmpty()) {
                        
                        queue.wait();
                    }
                }
            } catch (InterruptedException ex) {
                logger.error("Errore interrupt" + ex.getMessage());
            }
        }
    }
}
